package com.qfjy.project.weixin.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.qfjy.entity.po.User;
import com.qfjy.entity.po.WeiUser;
import com.qfjy.project.weixin.api.tuling.TuLingUtil;
import com.qfjy.project.weixin.api.wenzishibie.GeneralBasic;
import com.qfjy.project.weixin.bean.resp.image.ImageBean;
import com.qfjy.project.weixin.bean.resp.image.ImageMessage;
import com.qfjy.project.weixin.main.MenuManager;
import com.qfjy.project.weixin.util.crypto.AesUtil;
import com.qfjy.service.UserService;
import com.qfjy.service.WeiUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.qfjy.project.weixin.util.MessageUtil;


import com.qfjy.project.weixin.bean.resp.Article;
import com.qfjy.project.weixin.bean.resp.NewsMessage;
import com.qfjy.project.weixin.bean.resp.TextMessage;

@Service
public class CoreService {
	@Resource
	private TuLingUtil tuLingUtil;
	@Autowired
	private WeiUserService weiUserService;
	@Autowired
	private UserService userService;
	/**
	 * 处理微信发来的请求
	 *
	 * @param request
	 * @return
	 */
	public String processRequest(HttpServletRequest request) {
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "请求处理异常，请稍候尝试！";

			// xml请求解析 调用消息工具类MessageUtil解析微信发来的xml格式的消息，解析的结果放在HashMap里；
			Map<String, String> requestMap = MessageUtil.parseXml(request);

			// 发送方帐号（open_id） 下面三行代码是： 从HashMap中取出消息中的字段；
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			// 消息类型
			String msgType = requestMap.get("MsgType");

			// 回复文本消息 组装要返回的文本消息对象；
			TextMessage textMessage = new TextMessage();
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			textMessage.setFuncFlag(0);
			// 由于href属性值必须用双引号引起，这与字符串本身的双引号冲突，所以要转义
			// textMessage.setContent("欢迎访问<a
			// href=\"http://www.baidu.com/index.php?tn=site888_pg\">百度</a>!");
			// 将文本消息对象转换成xml字符串
			respMessage = MessageUtil.textMessageToXml(textMessage);
			/**
			 * 演示了如何接收微信发送的各类型的消息，根据MsgType判断属于哪种类型的消息；
			 */

			// 接收用户发送的文本消息内容
			String content = requestMap.get("Content");

			// 创建图文消息
			NewsMessage newsMessage = new NewsMessage();
			newsMessage.setToUserName(fromUserName);
			newsMessage.setFromUserName(toUserName);
			newsMessage.setCreateTime(new Date().getTime());
			newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
			newsMessage.setFuncFlag(0);

			// 文本消息
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {

				if ("范冰冰".equals(content)){
					//返回图片
					ImageMessage imageMessage = new ImageMessage();
					imageMessage.setFromUserName(toUserName);
					imageMessage.setToUserName(fromUserName);
					imageMessage.setMsgType(MessageUtil.REQ_MESSAGE_TYPE_IMAGE);
					imageMessage.setCreateTime(System.currentTimeMillis());
					ImageBean imageBean = new ImageBean();
					imageBean.setMediaId("TFjQmApuK_hgx5eCbVoRjY5bZkTo_2N7Qfy8Rn-sThOeGEmQS1HLIpRa6rbTDItF");
					imageMessage.setImage(imageBean);

					respMessage = MessageUtil.imageMessageToXml(imageMessage);
					return respMessage;
				}
				if ("lng".equals(content)){
					//返回图片
					ImageMessage imageMessage = new ImageMessage();
					imageMessage.setFromUserName(toUserName);
					imageMessage.setToUserName(fromUserName);
					imageMessage.setMsgType(MessageUtil.REQ_MESSAGE_TYPE_IMAGE);
					imageMessage.setCreateTime(System.currentTimeMillis());
					ImageBean imageBean = new ImageBean();
					imageBean.setMediaId("TFjQmApuK_hgx5eCbVoRjd2iT4TygpxYMJMwGn4Zpj3_yHVUhQ5evBeIXBWTKu-U");
					imageMessage.setImage(imageBean);

					respMessage = MessageUtil.imageMessageToXml(imageMessage);
					return respMessage;
				}
				if ("王者荣耀启动".equals(content)){
					//返回图片
					ImageMessage imageMessage = new ImageMessage();
					imageMessage.setFromUserName(toUserName);
					imageMessage.setToUserName(fromUserName);
					imageMessage.setMsgType(MessageUtil.REQ_MESSAGE_TYPE_IMAGE);
					imageMessage.setCreateTime(System.currentTimeMillis());
					ImageBean imageBean = new ImageBean();
					imageBean.setMediaId("TFjQmApuK_hgx5eCbVoRjcqX40na2-ac_h9QynvWHNlQ7YYxDkAciotYUFm2kijZ");
					imageMessage.setImage(imageBean);

					respMessage = MessageUtil.imageMessageToXml(imageMessage);
					return respMessage;
				}

				respContent = tuLingUtil.sendMessage(content);
//				respContent = "您发送的是文本消息！";
			}
			// 图片消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
				String picUrl = requestMap.get("PicUrl");
				respContent = GeneralBasic.generalBasic(picUrl);
//				respContent = "您发送的是图片消息！";
			}
			// 地理位置消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
				respContent = "您发送的是地理位置消息！";
			}
			// 链接消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
				respContent = "您发送的是链接消息！";
			}
			// 音频消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
				respContent = "您发送的是音频消息！";
			}
			// 事件推送
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {
				// 事件类型
				String eventType = requestMap.get("Event");
				// 订阅
				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {

					respContent = "欢迎关注微信公众号";
				}
				// 取消订阅
				else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {
					// TODO 取消订阅后用户再收不到公众号发送的消息，因此不需要回复消息
				}
				// 自定义菜单点击事件
				else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {
					// 事件KEY值，与创建自定义菜单时指定的KEY值对应
					String eventKey = requestMap.get("EventKey");

					if (eventKey.equals("11")) {
//						respContent = "菜单项被点击！";

						List<Article> articleList = new ArrayList<>();
						// 微信发送方
						String openid = fromUserName;
						WeiUser weiUser = weiUserService.selectWeiUserByOpenid(openid);
						User user = userService.selectUserByWid(weiUser.getId());
						Article article = new Article();

						if (user == null) {
							// 未登录

							// 单图文消息
							article.setTitle("未登录");
							article.setDescription("本平台需要用户登录才能访问,点击进入用户登录页面");
							article.setPicUrl(
									"https://ts1.cn.mm.bing.net/th/id/R-C.14a34b7a34577ee14c8aa0b3f8a96e05?rik=w0r9RHc26Ed3jA&riu=http%3a%2f%2fimg95.699pic.com%2fphoto%2f50155%2f3663.jpg_wh860.jpg&ehk=0jgyi7b4V2SmG1KaD73aAirLnznpcshyIy%2b8QB4PVvs%3d&risl=&pid=ImgRaw&r=0");
							article.setUrl(MenuManager.REAL_URL+"/page/userLogin?openid="+openid+"&wid="+weiUser.getId());

						} else {
							if (user.getRid() != 2) {
								// 不是抢单组
								// 单图文消息
								article.setTitle("您不是抢单组,暂无权限操作");
								article.setDescription("您不是抢单组,暂无权限操作");
								article.setPicUrl(
										"https://img95.699pic.com/photo/40028/0003.jpg_wh300.jpg");
								article.setUrl(MenuManager.REAL_URL + "/page/unauth");

							} else {
								// 抢单组
								Integer uid = user.getId();
								// 加密AES加密算法
								String encryptUid = AesUtil.encryptHexSet(String.valueOf(uid));

								// 单图文消息
								article.setTitle("欢迎您,"+user.getName()+",您可以进行抢单操作");
								article.setDescription("抢单相关教程,如何抢单");
								article.setPicUrl(
										"https://ts1.cn.mm.bing.net/th/id/R-C.5c6fc5a478340020eca733cebd09a31c?rik=KIDOb0rIiOSwIQ&riu=http%3a%2f%2fwww.kuaipng.com%2fUploads%2fpic%2fwater%2f17464%2fgoods_water_17464_698_698_.png&ehk=AVkcP4iMR3vdEuD1q9IjWUu%2ff99GA3xsnL9%2fbRHXiiE%3d&risl=&pid=ImgRaw&r=0");
								article.setUrl(MenuManager.REAL_URL + "/page/meetingGrabList?encryptUid="+encryptUid);

							}

						}
						articleList.add(article);
						// 设置图文消息个数
						newsMessage.setArticleCount(articleList.size());
						// 设置图文消息
						newsMessage.setArticles(articleList);
						// 将图文消息对象转换为XML字符串
						respMessage = MessageUtil.newsMessageToXml(newsMessage);
						return respMessage;

					}
					else if (eventKey.equals("10")) {

						List<Article> articleList = new ArrayList<Article>();

						// 单图文消息
						Article article = new Article();
						article.setTitle("是什么让西红柿价格飙升700%");
						article.setDescription("近一段时间以来,全球极端天气频发,导致农作物病虫害加剧,受此影响,可可,西红柿等农产品价格飙升");
						article.setPicUrl(
								"https://xhsc.app.xinhuanet.com/cms/xhharticle/image/20230829/b9a88d4c-6cad-4ac7-b193-6deb89f45554.png");
						article.setUrl("https://baijiahao.baidu.com/s?id=1775739358825899196");


						articleList.add(article);
						// 设置图文消息个数
						newsMessage.setArticleCount(articleList.size());
						// 设置图文消息
						newsMessage.setArticles(articleList);
						// 将图文消息对象转换为XML字符串
						respMessage = MessageUtil.newsMessageToXml(newsMessage);
						return respMessage;
					}

				}

			}

			// 组装要返回的文本消息对象；
			textMessage.setContent(respContent);
			// 调用消息工具类MessageUtil将要返回的文本消息对象TextMessage转化成xml格式的字符串；
			respMessage = MessageUtil.textMessageToXml(textMessage);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return respMessage;
	}

}
